<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>一体化组件打包服务</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <main>
    <div class="build-section">
      <div class="build-section__main">
        <!-- <h1 style="color: red;">暂时只发UAT版本</h1> -->
        <h3 class="time-line">一体化组件打包服务</h3>
        <h3 class="time-line hide">当前时间: <span class="time"></span></h3>

        <section class="params-section flex">
          <div class="param">
            组件包: 
            <select class="pkg-select" id="pkgSelect">
              <option selected value="srm">gys-external-srm</option>
              <option value="invoice">gys-external-invoice</option>
              <option value="cost">gys-external-cost</option>
            </select>
          </div>
          <div class="param">你的昵称: <input id="nickname" /></div>
          <div class="param" id="featBranch" title="功能分支，选填">待合并分支: <input id="branch" /></div>
        </section>


        <!-- <div class="tips">
            <p>
              请先合并 {你的功能分支} 到 <b>cmp-build</b>  分支
            </p>
          </div> -->
        <div class="buttons flex">
          <!-- <button class="btn" id="mergeBtn">拉取cmp-build分支</button> -->
          <button class="btn" id="buildSitBtn">打sit组件包</button>
          <button class="btn" id="buildUatBtn">打uat组件包</button>
        </div>

      </div>

      <div class="prod-wrap">
        <!-- <em>hotfix需自行合并到cmp-relase,并推送远端</em> -->
        <button class="btn" id="buildProdBtn">打生产包</button>
      </div>
    </div>

    <!-- <hr> -->

    <div class="output"></div>

    <button id="topBtn">Top</button>
  </main>
  <script src="common.js"></script>
  <script>
    var pkg = 'srm'

    function getPrefix() {
      return $('#pkgSelect').value || ''
    }

    function listenInputAndCache(id, isPrefix) {
      const input = $(`#${id}`)
      const cacheKey = `${isPrefix ? getPrefix() + ':' : ''}${id}`
      const cachedValue = localStorage[cacheKey]
      if (cachedValue) {
        input.value = cachedValue
      }

      input.addEventListener('input', ev => {
        const cacheKey = `${isPrefix ? getPrefix() + ':' : ''}${id}`
        localStorage[cacheKey] = ev.target.value
      })
    }

    function listenSelect(id) {
      const select = $(`#${id}`)
      select.addEventListener('change', event => {
        pkg = event.target.value;
        // const isHideFeatBranch = pkg === 'invoice'
        const isHideFeatBranch = false
        isHideFeatBranch ? hide('#featBranch') : show('#featBranch')

        $('#branch').value = localStorage[`${pkg}:branch`] || ''
      })
    }

    function getInputValue(id) {
      return $(`#${id}`).value
    }

    async function mergeBranch() {
      clearOutput()
      const stopScroll = autoScroll()
      const nickname = getInputValue('nickname')
      const branch = getInputValue('branch')
      hide('#mergeBtn')
      const res = await SRequest.post("/merge", { nickname, branch, pkg }, outputChunk, stopScroll);
      await sleep(3)
      show('#mergeBtn')
    }

    function showPublishDialog({pkg, version, env, reason = '', user}) {
      const dialog = $('#publish-dialog')
      dialog.classList.remove('hide')

      const con = `
      发版时间：${dateFormat()}
      发版原因：${reason}
      发版环境：${env} （outer）
      发版申请人: ${user}
      发版npm包及版本：${pkg}@${version}
      @酷玩蚊仔 @Spencer  ${pkg}组件包已更新，麻烦晚上帮忙发布一下${env} outer， 谢谢~~
      `
      $('.publish-msg').value = con
    }    

    async function buildComponent(qstr = '', clickedBtn) {
      const ok = window.confirm(`确定要构建 ${pkg.toUpperCase()} ${qstr.replace(/=.*$/, '').toUpperCase()} 包吗?`)
      if (!ok) return
      const query = getQuery(qstr)
      const isProd = query.prod

      // const envs = ['prod', 'sit', 'uat']
      // const btns = envs.reduce((ret, key) => { ret[key] = `build${capitalize(key)}Btn`}, {})

      clearOutput()

      const stopScroll = autoScroll()

      hide(clickedBtn)
      const nickname = getInputValue('nickname')
      const branch = getInputValue('branch')
      await sleep(3)
      const response = await SRequest.post('/build' + (qstr ? `?${qstr}` : ''), { nickname, branch, pkg }, outputChunk, stopScroll)
      show(clickedBtn)
    }

    function listenClick(btnId, callback) {
      const btn = $(`#${btnId}`)
      btn && btn.addEventListener('click', callback)
    }

    function main() {

      const cachedNickname = localStorage.nickname ?? ''
      if (!/^admin\-.+$/.test(cachedNickname)) {
        $('.prod-wrap').remove()
        // $('#mergeBtn').remove()
      }

      listenClick('mergeBtn', mergeBranch)
      listenClick('buildUatBtn', (event) => buildComponent('uat=1', event.target))
      listenClick('buildSitBtn', (event) => buildComponent('sit=1', event.target))
      listenClick('buildProdBtn', (event) => buildComponent('prod=1', event.target))

      $("#topBtn").addEventListener('click', () => {
        window.scrollTo(0, 0)
        autoScroll.stop()
      })

      $('.time').textContent = new Date().toLocaleString().replace(/\//g, '-')


      listenInputAndCache('nickname')
      listenInputAndCache('branch', true)

      listenSelect('pkgSelect')
    }


    main();
  </script>
</body>

</html>